package dormouse.fx.renderers;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;

import javax.imageio.ImageIO;

import org.apache.commons.vfs2.FileObject;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import dormouse.vfs.ui.renderers.IFileRenderer;

/**
 * This class is responsible for rendering the PDF document as a page.
 */
public class PDFRenderer extends BorderPane implements IFileRenderer<Node> {
	
	/** Class logger.*/
	private static final Logger log = LoggerFactory
			.getLogger(PDFRenderer.class);

	private static final String[] EXTS = new String[] { "pdf" };
	private List<BufferedImage> pageList = new ArrayList<>();
	
	/** The image view used to display the pages of the PDF. */
	private ImageView image = new ImageView();

	/**
	 * Constructor.
	 */
	public PDFRenderer() {
		setCenter(image);
	}

	@Override
	public void render(FileObject file) {
		try {
			PDDocument document = PDDocument.load(file.getContent()
					.getInputStream());

			List<PDPage> pages = document.getDocumentCatalog().getAllPages();
			for (int i = 0; i < pages.size(); i++) {
				PDPage singlePage = pages.get(i);

				BufferedImage buffImage = singlePage.convertToImage();
				pageList.add(buffImage);
			}
			InputStream is = (InputStream)ImageIO.createImageInputStream(pageList.get(0));
			image.setImage(new Image(is));
			
		} catch (IOException e) {
			log.debug(e.getMessage(), e);
		}

	}

	@Override
	public Node getComponent() {
		return this;
	}

	@Override
	public String[] getFileExtensions() {
		return EXTS;
	}

}
